const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

const users = {}; // 存储在线用户

// 静态文件托管
app.use(express.static('public'));

// Socket.io 连接处理
io.on('connection', (socket) => {
  // 用户加入
  socket.on('join', (username) => {
    if (users[username]) {
      socket.emit('username_error', '用户名已存在，请更换！');
    } else {
      users[username] = socket.id;
      socket.username = username;
      io.emit('user_joined', username);
      socket.emit('login_success');
    }
  });

  // 接收消息并广播
  socket.on('send_message', (message) => {
    io.emit('new_message', { user: socket.username, text: message });
  });

  // 用户断开
  socket.on('disconnect', () => {
    if (socket.username) {
      delete users[socket.username];
      io.emit('user_left', socket.username);
    }
  });
});

server.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});